package paintball;

import game.Player;

import org.json.JSONException;
import org.json.JSONObject;

import server.PacketInterpreter;
import controllers.PlayerController;

public class PaintballPacketInterpreter extends PacketInterpreter {

	public PaintballPacketInterpreter(Player player) {
		super(player);
	}

	@Override
	public void interpret(JSONObject input) throws JSONException {
		// Walk
		int code = input.getInt("Code");
		getPlayer().setReceived(true);
		switch(code) {
		case 0:
			// Movement
			movePlayer(input.getInt("Speed"));
			
			double rotation = input.getDouble("Angle");
			if (rotation != 0){ 
				double fixedRotation = fixRotation(rotation);
				setRotateDestination(fixedRotation);
			}
			if (input.getBoolean("Shoot"))
				shoot();
			break;
		case 1:
			
			int powerup = input.getInt("Powerup");
			switch(powerup){
			case 1:
				((PaintballPlayer)getPlayer()).powerUp1 = true;
				break;
			case 2:
				((PaintballPlayer)getPlayer()).powerUp2 = true;
				break;
			case 3:
				((PaintballPlayer)getPlayer()).powerUp3 = true;
				((PaintballPlayer)getPlayer()).setInvulnerable();
				break;
			}
			break;
		case 2:
			Vote(input.getInt("Vote"));
			break;
		case 3:
			// Set name
			getPlayer().setName(input.getString("Name"));
			PlayerController.addPlayer((PaintballPlayer)getPlayer());
			break;
		case 5:
			getPlayer().pong();
			break;
		case 6:
			getPlayer().disconnect("Player quit");
			break;
		}
	}
	
	private double fixRotation(double rotation) {
		double newRotation = rotation;
		if(rotation < 0) {
			newRotation = rotation+360; //Makes sure the rotation isn't > or < 360
		}		
		return newRotation;
	}

	private void setRotateDestination(double rotation) {
		getPlayer().setDesRotation(rotation);
		
	}

	private void Vote(int vote) {
		getPlayer().setVote(vote);
	}

	private void movePlayer(int speed) {
		PaintballPlayer player = (PaintballPlayer)getPlayer();
		if (speed > 0) {
			player.setMoveSpeed(speed/4);
			player.move = true;
		} else {
			player.move = false;
		}
	}

	
	private void shoot() {
		((PaintballPlayer)getPlayer()).shoot();
	}

}
